<!--
* @description wangEditor 富文本编译器 https://www.wangeditor.com/
* @fileName wangEditor.vue
* @author huangyu
* @date 2021/11/22 16:30:13
!-->
<template>
    <div class="WangEditor">
        <div :id="id"></div>
    </div>
</template>
<script>
import wangEditor from 'wangeditor'
import cloudbase from "@cloudbase/js-sdk";
export default {
    props:{
        desc:{
            type:String,
            default:""
        },
        isClear:{
            type:Boolean,
            default:false
        },
        height:{
            type:Number,
            default:500
        },
        id:{
            type: String,
            default: "IdWangEditor"
        }
    },
    components: {},
    data() {
        return {
            editor: null,
            editorData: 'IdWangEditor'
        }
    },
    model: {
      prop: 'desc',
      event:'change'
    },
    mounted() {
        const _this = this
        const editor = new wangEditor(`#${_this.id}`)

        editor.config.height = this.height
        editor.config.zIndex = 100

        // 配置 onchange 回调函数，将数据同步到 vue 中
        editor.config.onchange = (newHtml) => {
            this.editorData = newHtml
            this.$emit('change', this.editorData)
        }
        editor.config.customUploadImg = function (resultFiles) {
            // resultFiles 是 input 中选中的文件列表
            // 上传图片，返回结果，将图片插入到编辑器中
            _this.uploadMoreImg(resultFiles)
        }
        editor.config.pasteTextHandle = function (pasteStr) {
            // 对粘贴的文本进行处理，然后返回处理后的结果
            return pasteStr
        } 
        // 创建编辑器
        editor.create()
        this.editor = editor

        if (this.desc != this.editor.txt.html()) {
            this.editor.txt.html(this.desc)
        }
    },
    methods: {
        uploadMoreImg(resultFiles){
            // window.console.log(resultFiles[0])
            let params = resultFiles[0]
            const isJPG = params.type === 'image/jpeg' || params.type === 'image/png';
            const isLt7M = params.size / 1024 / 1024 < 7;
            // window.console.log(isJPG,isLt7M)
            if(!isJPG){
                this.$message.error("只能上传 JPG 或 PNG 格式")
                return
            }
            if (!isLt7M) {
                this.$message.error('上传图片大小不能超过 7MB!');
                return
            }

            var year = new Date().getFullYear()
            var month = new Date().getMonth() + 1
            var day = new Date().getDate()
            var time = new Date().getTime().toString()
            if(day<10){
                day = "0"+day.toString()
            }
            var date = year.toString()+month.toString()+day.toString()
            let path = "WebServiceFiles/MyImage/"+year+"/"+date+"/"+time

            if(params.type === 'image/jpeg'){
                path = path+'.jpg'
            }
            if(params.type === 'image/png'){
                path = path+'.png'
            }

            const app = cloudbase.init({
                env: "web-cloud0713-6g519i65f479e638"
            });

            app
            .uploadFile({
                cloudPath: path,
                filePath: params,
            })
            .then((result) => {
                // 上传结果
                if(result){
                    this.$message.success("上传成功！")
                    let url = result.download_url
                    const img = '<p><img src=' +url+' /></p>'
                    // 插入光标位置
                    this.editor.cmd.do('insertHTML',img)
                }
            }).catch(function (error) {
                alert(error)
            });
        },
        
        initDataHtml(){
            // window.console.log(this.dataHtml)
            this.$nextTick(()=>{
                this.editor.txt.clear()
                this.editor.txt.html(this.dataHtml)
            })
        },
    },
    // beforeDestroy() {
    //     // 调用销毁 API 对当前编辑器实例进行销毁
    //     this.editor.destroy()
    //     this.editor = null
    // },
    watch:{
        isClear(val){
            if (val){
                this.editor.txt.clear()
            }
        },
        desc(value) {
            if (value != this.editor.txt.html()) {
                this.editor.txt.html(this.desc)
            }
        }
    },
}
</script>

<style scoped lang="less">
</style>